<?php

namespace app\admin\controller\exam;

use app\admin\model\exam\CateModel;
use app\admin\model\school\Admin;
use app\common\controller\Backend;
use fast\Tree;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;

/**
 * 试题分类
 * @icon fa fa-circle-o
 */
class Cate extends Backend
{
    protected $noNeedRight = ['selectpage', 'getQuestionCate'];

    /**
     * CateModel模型对象
     * @var \app\admin\model\exam\CateModel
     */
    protected $model = null;

    public function _initialize()
    {
        parent::_initialize();
        $this->model = new \app\admin\model\exam\CateModel;
        $query       = $this->model->order('sort asc,id asc');

        $kind = input('kind/s', 'all');
        if ($kind != 'all') {
            $query->where('kind', $kind);
        }

        $tree = Tree::instance();
        $tree->init(collection($query->select())->toArray(), 'parent_id');
        $this->parentlist = $tree->getTreeList($tree->getTreeArray(0), 'name');

        $this->view->assign("kindList", $this->model->getKindList());
        $this->view->assign("parentList", $this->parentlist);
        $this->view->assign("usesList", $this->model->getUsesList());
        $this->view->assign("defaultList", $this->model->getIsDefault());
        $this->view->assign("deleteList", $this->model->getDelete());
    }

    public function import()
    {
        parent::import();
    }



    /**
     * 默认生成的控制器所继承的父类中有index/add/edit/del/multi五个基础方法、destroy/restore/recyclebin三个回收站方法
     * 因此在当前控制器中可不用编写增删改查的代码,除非需要自己控制这部分逻辑
     * 需要将application/admin/library/traits/Backend.php中对应的方法复制到当前控制器,然后进行修改
     */

    /**
     * 查看
     */
    public function index()
    {
        //设置过滤方法
        $this->request->filter(['strip_tags']);
        if ($this->request->isAjax()) {
            //如果发送的来源是Selectpage，则转发到Selectpage
            // if ($this->request->request('keyField')) {
            //     return $this->selectpage();
            // }
            list($where, $sort, $order, $offset, $limit) = $this->buildparams();

            $search = $this->request->request("search");
            $kind   = $this->request->request("kind");
            $parent_id   = $this->request->request("parent_id");
            //构造父类select列表选项数据
            $list = [];

            foreach ($this->parentlist as $k => $v) {
                /*if ($search) {
                    if ($v['kind'] == $kind) {
                        $list[] = $v;
                    }
                } else {
                    $list[] = $v;
                }*/
                if($parent_id)
                {
                    if ($v['parent_id'] == $parent_id)
                    {
                        $list[] = $v;
                        foreach ($this->parentlist as $kk => $vv)
                        {
                            if ($vv['parent_id'] == $v['id'])
                            {
                                $list[] = $vv;
                                foreach ($this->parentlist as $kkk => $vvv)
                                {
                                    if ($vvv['parent_id'] == $vv['id'])
                                    {
                                        $list[] = $vvv;
                                    }
                                }
                            }
                        }
                    }
                }
                else
                {
                    if ($v['parent_id'] == 0) {
                        $list[] = $v;
                    }
                }
            }

            $total  = count($list);
            $result = array("total" => $total, "rows" => $list);

            return json($result);
        }
        return $this->view->fetch();
    }

    /**
     * Selectpage搜索
     * @internal
     */
    public function selectpage()
    {
        return parent::selectpage();
    }

    /**
     * 获取有题目的分类
     * @internal
     */
    public function getQuestionCate()
    {
        if ($cate_ids = $this->request->request("keyValue", "")) {
            $list = CateModel::whereIn('id', $cate_ids)->select();
        } else {
            $ids  = Db::name('exam_question')->group('cate_id')->field('cate_id')->select();
            $list = $ids ? CateModel::whereIn('id', array_column($ids, 'cate_id'))->select() : [];
        }
        return json(['list' => $list, 'total' => count($list)]);
    }


    /**
     * 添加
     */
    public function add()
    {
        
        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                
                if($params['parent_id_t'] != 0)
                {
                    $params['parent_id'] = $params['parent_id_t'];
                }
                unset($params['parent_id_t']);
//                dump($params);die;
                if ($this->dataLimit && $this->dataLimitFieldAutoFill) {
                    $params[$this->dataLimitField] = $this->auth->id;
                }
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.add' : $name) : $this->modelValidate;
                        $this->model->validateFailException(true)->validate($validate);
                    }
                    //记录学校id集合
                    $schoolIds = $params['school_ids'];
                    unset($params['school_ids']);

                    $this->setLevel($params);
                    $result = $this->model->allowField(true)->save($params);

                    if($params['parent_id'] == 0)
                    {
                        $cate_list = Db::name('exam_cate')->where(['name'=>$params['name']])->order('id desc')->find();
                        $add_data = [
                            'name' => $params['name'],
                            'createtime' => time(),
                            'updatetime' => time(),
                            'cate_id' => $cate_list['id'],
                            'uid' => $schoolIds??''
                        ];
                        Db::name('classes_tiku')->insert($add_data);
                    }
                    if ($schoolIds) {
                        //查询所有需修改学校的数据
                        $db2 = new Admin();
                        $schooleData = $db2->whereIn('id', $schoolIds)->field('id,tiku_id')->select();
                        $schoolUpData = [];
                        //拼装学校表修改数据
                        $tiku = $result->id;
                        foreach ($schooleData as $v) {
                            $schoolUpData[] = ['id'=>$v['id'], 'tiku_id'=>$v['tiku_id'].','.$tiku];
                        }
                        if ($schoolUpData) {
                            $schoolUpdateRes = $db2->saveAll($schoolUpData);
                            if ($schoolUpdateRes === false) {
                                Db::rollback();
                                $db2->rollback();
                                $this->error(__('Update School Bind fail'));
                            }
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were inserted'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
        $parentlist = Db::name('exam_cate')->where(['parent_id'=>0,'deletetime'=>null])->select();
        $this->view->assign("parentList", $parentlist);
        $this->view->assign('schoolList',[
            'ids' => '',
            'names' => ''
        ]);
        return $this->view->fetch();
    }
    public function son_cate()
    {
        if ($this->request->isPost()) {
            $params = $this->request->post("");
            if($params['qid'] == 0){
                return json(['code'=>1,'msg'=>'','list'=>[]]);
            }
            $list = Db::name('exam_cate')->where(['parent_id'=>$params['qid'],'deletetime'=>null])->select();
            if(!empty($list))
            {
                return json(['code'=>100,'msg'=>'','list'=>$list]);
            }
            return json(['code'=>1,'msg'=>'','list'=>[]]);
        }
    }

    /**
     * 编辑
     */
    public function edit($ids = null)
    {
        $row = $this->model->get($ids);
        if (!$row) {
            $this->error(__('No Results were found'));
        }
        $adminIds = $this->getDataLimitAdminIds();
        if (is_array($adminIds)) {
            if (!in_array($row[$this->dataLimitField], $adminIds)) {
                $this->error(__('You have no permission'));
            }
        }

        //查询题库表
        $tiku = Db::name('classes_tiku')->where('cate_id', $ids)->value('id');
        //查询绑定学校数据
        $db2 = new Admin();
        $school = $db2->where('find_in_set(:id, tiku_id)', ['id'=>$tiku])->select();
        //拼装之前选中的可用学校数据
        $schooldList = [
            'ids' => '',
            'names' => '全部可用'
        ];
        $oldSchoolIds = [];
        if ($school) {
            $oldSchoolIds = array_column($school, 'id');
            $schooldList['ids'] = implode($oldSchoolIds, ',');
            $schooldList['names'] = implode(array_column($school, 'nickname'), ',');
        }

        if ($this->request->isPost()) {
            $params = $this->request->post("row/a");
            if ($params) {
                $params = $this->preExcludeFields($params);
                $result = false;
                Db::startTrans();
                try {
                    //是否采用模型验证
                    if ($this->modelValidate) {
                        $name     = str_replace("\\model\\", "\\validate\\", get_class($this->model));
                        $validate = is_bool($this->modelValidate) ? ($this->modelSceneValidate ? $name . '.edit' : $name) : $this->modelValidate;
                        $row->validateFailException(true)->validate($validate);
                    }
                    //如果id不为空则为部分可用，否则为全部
                    if (strlen($params['school_ids']) > 0) {
                        $params['uses'] = 'ONLY_MEMBER';
                    }

                    //记录学校id集合
                    $schoolIds = $params['school_ids'];
                    unset($params['school_ids']);
                    if(!empty($params['remark']))
                    {
                        Db::name('exam_question')->where('cate_id','in',$ids)->update(['describe'=>$params['remark']]);
                    }

                    $this->setLevel($params, $row);
                    $result = $row->allowField(true)->save($params);

                    //修改题库绑定学校id
                    $tikuRes = Db::name('classes_tiku')->where('id',$tiku)->update(['uid'=>$schoolIds]);
                    if ($tikuRes === false) {
                        Db::rollback();
                        $this->error(__('Bind User Error'));
                    }

                    //查询所有需修改学校的数据
                    $schooleData = $db2->whereIn('id', $schoolIds)->field('id,tiku_id')->select();
                    $schoolUpData = [];
                    //拼装学校表修改数据
                    foreach ($schooleData as $v) {
                        //历史绑定记录中不包含的话，则不做变更
                        if (!strpos($v['tiku_id'], (string)$tiku)) {
                            $schoolUpData[] = ['id'=>$v['id'], 'tiku_id'=>$v['tiku_id'].','.$tiku];
                        }
                    }
                    if ($schoolUpData) {
                        $schoolUpdateRes = $db2->saveAll($schoolUpData);
                        if ($schoolUpdateRes === false) {
                            Db::rollback();
                            $db2->rollback();
                            $this->error(__('Update School Bind fail'));
                        }
                    }

                    $schoolDelBindIds = [];
                    //历史id不在即将绑定id集合中，则记录删除id
                    $schoolIdsArr = explode(',', $schoolIds);
                    foreach($oldSchoolIds as $oldVal) {
                        if (!in_array($oldVal, $schoolIdsArr)) {
                            $schoolDelBindIds[] = $oldVal;
                        }
                    }
                    //查询需解除绑定数据
                    $needJbData = $db2->whereIn('id', $schoolDelBindIds)->field('id, tiku_id')->select();
                    $needUpData = [];
                    foreach($needJbData as $needVal) {
                        $tikuIdArr = explode(',', $needVal['tiku_id']);
                        $needUpData[] = [
                            'id' => $needVal['id'],
                            'tiku_id' => implode(',', array_diff($tikuIdArr, [$tiku]))
                        ];
                    }
                    if ($needUpData) {
                        $needUpdateRes = $db2->saveAll($needUpData);
                        if ($needUpdateRes === false) {
                            Db::rollback();
                            $db2->rollback();
                            $this->error(__('Deal Unbind School fail'));
                        }
                    }
                    
                    Db::commit();
                } catch (ValidateException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (PDOException $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                } catch (\Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if ($result !== false) {
                    $this->success();
                } else {
                    $this->error(__('No rows were updated'));
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
       
        
        $this->view->assign("row", $row);
        $this->view->assign('schoolList',$schooldList);
        return $this->view->fetch();
    }

    /**
     * 添加|修改时获取学校列表
     */
    public function selectSchoolList()
    {
        $db2 = Db::connect('db2');
        $where['b.group_id'] = ['=',2];
        $list = $db2->table('fa_admin a')
            ->join('fa_auth_group_access b','b.uid=a.id')
            ->where($where)
            ->column('nickname', 'id');
        return $list;
    }

    /**
     * 设置层级
     * @param $params
     */
    protected function setLevel(&$params, $row = null)
    {
        $params['parent_id'] = $params['parent_id'] ?? 0;

        if (!$params['parent_id']) {
            $params['level'] = 1;
        } else {
            $parent = CateModel::get($params['parent_id']);

            // 编辑时
            if ($row) {
                if ($params['parent_id'] == $row['id']) {
                    throw new \Exception('不能将当前分类设置为父级分类');
                }
                if ($parent['kind'] != $params['kind']) {
                    throw new \Exception('不能将当前分类设置为其他种类的下级');
                }
                $child_ids = CateModel::where('parent_id', $row['id'])->column('id');
                if (in_array($params['parent_id'], $child_ids)) {
                    throw new \Exception('不能将当前分类的子级设置为当前分类的父级');
                }
            }

            if ($parent['level'] == 1) {
                $params['level'] = 2;
            } else if ($parent['level'] == 2) {
                $params['level'] = 3;
            }else if ($parent['level'] == 3) {
                $params['level'] = 4;
            } else {
                throw new \Exception('错误：最多添加4级分类，请重新选择父级类别');
            }
        }
    }
    
    public function del_all()
    {
        $ids = $this->request->post("ids");
        $data = [
            'deletetime' => time(),
        ];
        $cateList = Db::name('exam_cate')->where('id','in',$ids)->select();
        foreach($cateList as $cateVal) {
            if ($cateVal['is_delete'] == 'NO') {
                return json(['code'=>0,'data'=>'','msg'=>'ID为'.$cateVal['id'].'的数据禁止删除','url'=>'/abdmin.php/exam.cate/del_all','wait'=>3]);
            }
        }
        //一级
        Db::name('exam_cate')->where('id','in',$ids)->update($data);
        Db::name('exam_question')->where('cate_id','in',$ids)->update($data);
        $where['parent_id'] = ['in',$ids];
        $where['deletetime'] = null;

        $list = Db::name('exam_cate')->where($where)->select();
        $son_ids = '';
        $son_son_ids = '';
        $son_son_son_ids = '';
        $sids = '';
        $notAllowDelId = 0;
        if(!empty($list))
        {
            foreach ($list as $k => $v)
            {
                if ($v['is_delete'] == 'NO') {
                    $notAllowDelId = $v['id'];
                }
                $son_ids .= $v['id'].',';
            }
            if ($notAllowDelId>0) {
                Db::rollback();
                return json(['code'=>0,'data'=>'','msg'=>'下级分类ID为'.$v['id'].'的数据禁止删除','url'=>'/abdmin.php/exam.cate/del_all','wait'=>3]);
            }
            $son_ids = trim($son_ids,',');
            $son_where['parent_id'] = ['in',$son_ids];
            $son_where['deletetime'] = null;
            //二级
            Db::name('exam_cate')->where($where)->update($data);
            Db::name('exam_question')->where('cate_id','in',$son_ids)->update($data);

            $son_list = Db::name('exam_cate')->where($son_where)->select();

            if(!empty($son_list))
            {
                foreach ($son_list as $k => $v)
                {
                    if ($v['is_delete'] == 'NO') {
                        $notAllowDelId = $v['id'];
                    }
                    $son_son_ids .= $v['id'].',';
                }
                if ($notAllowDelId>0) {
                    Db::rollback();
                    return json(['code'=>0,'data'=>'','msg'=>'下级分类ID为'.$v['id'].'的数据禁止删除','url'=>'/abdmin.php/exam.cate/del_all','wait'=>3]);
                }
                $son_son_ids = trim($son_son_ids,',');
                $son_son_where['parent_id'] = ['in',$son_son_ids];
                $son_son_where['deletetime'] = null;
                //三级
                Db::name('exam_cate')->where($son_where)->update($data);
                Db::name('exam_question')->where('cate_id','in',$son_son_ids)->update($data);

                $son_son_list = Db::name('exam_cate')->where($son_son_where)->select();

                if(!empty($son_son_list))
                {
                    foreach ($son_son_list as $k => $v)
                    {
                        if ($v['is_delete'] == 'NO') {
                            $notAllowDelId = $v['id'];
                        }
                        $son_son_son_ids .= $v['id'].',';
                    }
                    if ($notAllowDelId>0) {
                        Db::rollback();
                        return json(['code'=>0,'data'=>'','msg'=>'下级分类ID为'.$v['id'].'的数据禁止删除','url'=>'/abdmin.php/exam.cate/del_all','wait'=>3]);
                    }
                    $son_son_son_ids = trim($son_son_son_ids,',');
                    $son_son_son_where['parent_id'] = ['in',$son_son_son_ids];
                    $son_son_son_where['deletetime'] = null;
                    //四级
                    Db::name('exam_cate')->where($son_son_where)->update($data);
                    Db::name('exam_question')->where('cate_id','in',$son_son_son_ids)->update($data);

                    $slist = Db::name('exam_cate')->where($son_son_son_where)->select();

                    if(!empty($slist))
                    {
                        foreach ($slist as $k => $v)
                        {
                            $sids .= $v['id'].',';
                        }
                        $sids = trim($sids,',');
                        Db::name('exam_question')->where('cate_id','in',$sids)->update($data);
                    }
                }
            }
        }
        Db::name('classes_tiku')->where('cate_id','in',$ids)->delete();
        return json(['code'=>1,'data'=>'','msg'=>'','url'=>'/abdmin.php/exam.cate/del_all','wait'=>3]);
    }
    public function expandlink()
    {
        $id = $this->request->request("id");
        if ($this->request->isPost()) {
            $cate_id = $this->request->request("cate_id");
            $other_url = $this->request->request("other_url");
            $other_name = $this->request->request("other_name");

            Db::name('exam_question')->where('cate_id',$cate_id)->update(['other_url'=>$other_url,'other_name'=>$other_name]);
//            $this->success();
            echo "<script>alert('修改成功');parent.location.reload();</script>";die;
        }
        $this->view->assign("cate_id", $id);
        return $this->view->fetch();
    }

    /**
     * 复制分类
     */
    public function copycate()
    {
        $ids = $this->request->post("ids");
        if($ids) {
            Db::startTrans();
            foreach(explode(',', $ids) as $v) {
                $res = $this->doCopy($v, true);
                if (!$res) {
                    Db::rollback();
                    break;
                } 
            }
            if ($res) {
                Db::commit();
                $this->success();
            }
            $this->error(__('Copy Fail'));
        }
        $this->error(__('Param Error Id'));
    }

    /**
     * 递归处理复制分类
     * @param int   $id 需要处理的id
     * @param init  $isFirst 是否为初次
     * @param init  $parentId 上级id
     */
    public function doCopy($id=0, $isFirst=false, $parentId=0)
    {
        $result = true;
        //查询当前分类
        $cate = $this->model->where('id', $id)->find();
        if ($cate) {
            //格式化数据
            $newData = $this->initCopyData($cate, $isFirst?$cate['parent_id']:$parentId);
            //插入数据
            $newId = $this->model->insertGetId($newData);
            if (!$newId) return false;
            //查询当前数据的下级数据
            $childCate = $this->model->where('parent_id', $id)->select();
            foreach ($childCate as $v) {
                $res = $this->doCopy($v['id'], false, $newId);
                if (!$res) {
                    $result = false;
                    break;
                }
            }
        }
        return $result;
    }

    /**
     * 格式化需要插入的数据
     */
    public function initCopyData($data, $parent_id)
    {
        $newData = [
            'kind' => $data['kind'],
            'level' => $data['level'],
            'name' => $data['name'].'-副本1',
            'parent_id' => $parent_id,
            'sort' => $data['sort'],
            'remark' => $data['remark'],
            'uses' => $data['uses'],
        ];
        return $newData;
    }

}
